﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Giaiphongmatbang.DataModel;

namespace Giaiphongmatbang.BLL
{
    public class InventoriesRepository
    {
        private QLGPMBEntities data = new QLGPMBEntities();

        public IEnumerable<Inventory> GetAll(int pageSize, int pageNumber, ref int totalRow)
        {
            var results = from p in data.Inventories
                          select p;
            totalRow = results.Count();
            return results.OrderByDescending(p=>p.ProjectID).OrderBy(p=>p.CMND).Skip((pageNumber - 1) * pageSize).Take(pageSize);
        }

        public Inventory GetByID(int ID)
        {
            var result = from p in data.Inventories
                         where p.InventID == ID
                         select p;
            return result.FirstOrDefault();
        }

        public IEnumerable<Inventory> GetByProjectID(int ID)
        {
            var results = from p in data.Inventories
                          where p.Project.ProjectID == ID
                          select p;
            return results;
        }

        public IEnumerable<Inventory> GetByProjectIDAndPersonID(int projectID, int personID)
        {
            return data.Inventories.Where(p => data.ComponentInventories.Any(q => q.PersonInventories.Any(u => u.PersonID == personID)) && p.ProjectID == projectID);
        }

        public void Insert(Inventory i)
        {
            data.AddToInventories(i);
        }

        public void DeleteByID(int id)
        {
            var obj = GetByID(id);
            if (obj != null)
            {
                data.DeleteObject(obj);
            };
        }

        public void Save()
        {
            data.SaveChanges();
        }
    }
}